<?php

declare(strict_types=1);

namespace App\Model;

use App\Model\Setting\SettingUserQuestion;
use Hyperf\DbConnection\Model\Model;

/**
 * 用户专访
 */
class UserQa extends Model
{
    protected $table = 'user_qa';
    protected $fillable = ['user_id', 'question_id', 'answer', 'flag'];

    function questionInfo()
    {
        return $this->belongsTo(SettingUserQuestion::class, 'question_id', 'id');
    }

    static function addRecord($userId = 0, $questionId = 0, $answer = '')
    {
        if (!$questionId) return false;
        $where = [
            'user_id' => $userId,
            'question_id' => $questionId,
        ];
        $upInfo = $answer ? ['answer' => $answer, 'flag' => 1] : ['answer' => '', 'flag' => 0];
        $info = array_merge($where, $upInfo);
        $ret = self::updateOrCreate($where, $info);
        return $ret;
    }

    static function getList($userId = 0, $gender = -1)
    {
        $where = ['user_id' => $userId, 'flag' => 1];
        $validQuesitonIds = SettingUserQuestion::getQuestionIds($gender);
        return self::where($where)->whereIn('question_id', $validQuesitonIds)->select(['answer', 'question_id'])->get()->toArray();
    }

    static function getDetailList($userId = 0)
    {
        $where = ['user_id' => $userId, 'flag' => 1];
        $data = self::where($where)->get();
        $result = [];
        foreach ($data as $item) {
            if (!$item->questionInfo) continue;
            $result[] = [
                'question' => $item->questionInfo->question,
                'answer' => $item->answer,
            ];
        }
        return $result;
    }
}
